import React, { useState, useEffect } from 'react'
import { Table, Button, Space, Modal, Form, Input, DatePicker, Select, Tag, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'

const { Option } = Select

function Appointments() {
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [editingAppointment, setEditingAppointment] = useState(null)
    const [form] = Form.useForm()
    const [appointments, setAppointments] = useState([
        {
            id: 'A001',
            memberName: '张三',
            service: '剪发',
            stylist: '王师傅',
            appointmentTime: '2024-03-20 14:00',
            status: '待服务'
        }
    ])

    useEffect(() => {
        if (!isModalVisible) {
            form.resetFields()
        }
    }, [isModalVisible, form])

    const handleEdit = (record) => {
        setEditingAppointment(record)
        setTimeout(() => {
            form.setFieldsValue({
                ...record,
                appointmentTime: dayjs(record.appointmentTime, 'YYYY-MM-DD HH:mm')
            })
        }, 0)
        showModal()
    }

    const handleDelete = (record) => {
        Modal.confirm({
            title: '确认取消',
            content: `确定要取消${record.memberName}的预约吗？`,
            onOk() {
                setAppointments(appointments.map(item =>
                    item.id === record.id
                        ? { ...item, status: '已取消' }
                        : item
                ))
                message.success('预约已取消')
            }
        })
    }

    const handleComplete = (record) => {
        setAppointments(appointments.map(item =>
            item.id === record.id
                ? { ...item, status: '已完成' }
                : item
        ))
        message.success('服务已完成')
    }

    const showModal = () => {
        setIsModalVisible(true)
        if (!editingAppointment) {
            form.resetFields()
        }

    }

    const handleCancel = () => {
        console.log(editingAppointment)
        setIsModalVisible(false)
        setEditingAppointment(null)
        form.resetFields()

    }

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields()
            if (!values.appointmentTime) {
                message.error('请选择预约时间')
                return
            }

            const formattedValues = {
                ...values,
                appointmentTime: values.appointmentTime.format('YYYY-MM-DD HH:mm')
            }

            if (editingAppointment) {
                setAppointments(appointments.map(item =>
                    item.id === editingAppointment.id
                        ? { ...item, ...formattedValues }
                        : item
                ))
                message.success('预约已更新')
            } else {
                const newAppointment = {
                    id: `A${String(appointments.length + 1).padStart(3, '0')}`,
                    ...formattedValues,
                    status: '待服务'
                }
                setAppointments([...appointments, newAppointment])
                message.success('预约已创建')
            }
            handleCancel()
        } catch (error) {
            console.error('Validate Failed:', error)
            const errorFields = error.errorFields
            if (errorFields && errorFields.length > 0) {
                message.error(errorFields[0].errors[0])
            }
        }
    }

    const columns = [
        {
            title: '预约编号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '会员姓名',
            dataIndex: 'memberName',
            key: 'memberName',
        },
        {
            title: '预约项目',
            dataIndex: 'service',
            key: 'service',
        },
        {
            title: '发型师',
            dataIndex: 'stylist',
            key: 'stylist',
        },
        {
            title: '预约时间',
            dataIndex: 'appointmentTime',
            key: 'appointmentTime',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={
                    status === '已完成' ? 'success' :
                        status === '已取消' ? 'error' :
                            status === '待服务' ? 'processing' : 'default'
                }>
                    {status}
                </Tag>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    {record.status === '待服务' && (
                        <>
                            <Button type="link" onClick={() => handleComplete(record)}>
                                完成
                            </Button>
                            <Button type="link" onClick={() => handleEdit(record)}>
                                编辑
                            </Button>
                            <Button type="link" danger onClick={() => handleDelete(record)}>
                                取消
                            </Button>
                        </>
                    )}
                </Space>
            ),
        },
    ]

    return (
        <div>
            <div style={{ marginBottom: 16 }}>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={showModal}
                >
                    新增预约
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={appointments}
                rowKey="id"
                pagination={{
                    pageSize: 10,
                    showTotal: (total) => `共 ${total} 条记录`
                }}
            />

            <Modal
                title={editingAppointment ? '编辑预约' : '新增预约'}
                open={isModalVisible}
                onOk={handleSubmit}
                onCancel={handleCancel}
                maskClosable={false}
                destroyOnClose={false}
                className="custom-modal"
                transitionName=""
                maskTransitionName=""
                modalRender={(modal) => (
                    <div onClick={(e) => e.stopPropagation()}>
                        {modal}
                    </div>
                )}
                footer={[
                    <Button
                        key="cancel"
                        onClick={handleCancel}
                        className="modal-btn"
                    >
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        onClick={handleSubmit}
                        className="modal-btn btn-shine"
                    >
                        确定
                    </Button>
                ]}
            >
                <Form
                    form={form}
                    layout="vertical"
                    preserve={false}
                    className="custom-form"
                >
                    <Form.Item
                        name="memberName"
                        label="会员姓名"
                        rules={[{ required: true, message: '请选择会员' }]}
                    >
                        <Select placeholder="请选择会员">
                            <Option value="张三">张三</Option>
                            <Option value="李四">李四</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="service"
                        label="预约项目"
                        rules={[{ required: true, message: '请选择预约项目' }]}
                    >
                        <Select placeholder="请选择预约项目">
                            <Option value="剪发">剪发</Option>
                            <Option value="染发">染发</Option>
                            <Option value="烫发">烫发</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="stylist"
                        label="发型师"
                        rules={[{ required: true, message: '请选择发型师' }]}
                    >
                        <Select placeholder="请选择发型师">
                            <Option value="王师傅">王师傅</Option>
                            <Option value="李师傅">李师傅</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="appointmentTime"
                        label="预约时间"
                        rules={[{ required: true, message: '请选择预约时间' }]}
                    >
                        <DatePicker
                            showTime
                            format="YYYY-MM-DD HH:mm"
                            style={{ width: '100%' }}
                            disabledDate={(current) => {
                                return current && current < dayjs().startOf('day')
                            }}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default Appointments 